﻿using DevExpress.DataAccess.Native.Data;
using DevExpress.Utils.Menu;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using Newtonsoft.Json.Linq;
using SX_MesProject.Dtos.YSDtos;
using SX_MesProject.ProductionPlanManagement;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static SX_MesProject.HttpClientHelper;

namespace SX_MesProject.YS
{
    public partial class ProductionPlan : DevExpress.XtraEditors.XtraForm
    {
        private object currentRowData;
        private void gridControl1_Click(object sender, EventArgs e)
        {

        }
        public ProductionPlan()
        {
            InitializeComponent();
            textEdit1.Text = DateTime.Now.ToString("yyyy-MM-dd");
            textEdit2.Text = "2";
        }
        private async void ProductionPlan_LoadAsync(object sender, EventArgs e)
        {
            await ProductionPlanListAsync(textEdit1.Text, textEdit2.Text);
        }

        private async Task<System.Data.DataTable> ProductionPlanListAsync(string aa, string bb)
        {
            using (HttpClient client = new HttpClient())
            {
                aa = textEdit1.Text;
                bb = textEdit2.Text;
                client.BaseAddress = new Uri("https://localhost:44556/");
                HttpResponseMessage response;

                if (string.IsNullOrEmpty(aa) && string.IsNullOrEmpty(bb))
                {
                    response = await client.GetAsync("GetProductionPlanList?days=3");
                }
                else
                {
                    response = await client.GetAsync("GetProductionPlanList?startDateString=" + aa + "&days=" + bb);
                }

                if (response.IsSuccessStatusCode)
                {
                    string content = await response.Content.ReadAsStringAsync();
                    JArray jsonArray = JArray.Parse(content);
                    System.Data.DataTable dataTable = new System.Data.DataTable();

                    if (jsonArray.Count > 0)
                    {
                        // 获取第一条记录的键值对作为列名
                        foreach (JProperty column in jsonArray[0])
                        {
                            dataTable.Columns.Add(column.Name);
                        }

                        // 遍历每一条记录，并添加到 DataTable 中
                        foreach (JObject jsonObject in jsonArray)
                        {
                            DataRow row = dataTable.NewRow();
                            foreach (JProperty column in jsonObject.Properties())
                            {
                                row[column.Name] = column.Value.ToString(); // 确保填充数据时转换为字符串
                            }
                            dataTable.Rows.Add(row);
                        }

                        // 使用 Invoke 确保 UI 在主线程中更新
                        gridControl1.Invoke((Action)(() =>
                        {
                            // 强制刷新列名
                            gridView1.Columns.Clear();  // 清除现有列

                            // 更新数据源
                            gridControl1.DataSource = dataTable;
                            gridControl1.RefreshDataSource();  // 刷新数据源
                            gridControl1.Refresh();  // 刷新控件显示

                            // 如果需要，手动设置列名（例如按特定格式）
                            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView1.Columns)
                            {
                                column.Caption = column.FieldName; // 或者可以根据实际需要设置列名
                            }
                        }));
                        return dataTable;
                    }
                }
                else
                {
                    MessageBox.Show("请求失败，状态码: " + response.StatusCode);
                }
            }
            return null; // 请求失败时返回 null
        }

        private void checkButton1_Click(object sender, EventArgs e)
        {

            ProductionPlan_LoadAsync(sender, e);
        }
        public static class GlobalData
        {
            public static string ColumnName { get; set; }
            public static string RowName {  get; set; }
           
        }
        private void gridView1_PopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e)
        {

            if (e.HitInfo.InRowCell)
            {
                var rowHandle = e.HitInfo.RowHandle;
                var column = e.HitInfo.Column;  // 获取当前点击的列
                string columnName = column.FieldName;  // 获取列名
                var columnValue = gridView1.GetRowCellValue(rowHandle, columnName);  // 获取该列的值
                GlobalData.ColumnName = column.ToString();
              
                // 打印列名和对应的值
                //MessageBox.Show($"列名: {columnName}, 值: {columnValue}");
                // 获取当前行的数据对象
                var rowData = gridView1.GetRow(rowHandle);  // 获取行的数据对象
                // 确保 rowData 是 DataRowView 类型
                var dataRowView = rowData as DataRowView;
                if (dataRowView != null)
                {
                    // 使用列索引访问
                    var value1 = dataRowView[0];  // 访问第一列
                    GlobalData.RowName= value1.ToString();
                }
                else
                {
                    MessageBox.Show("数据行不是 DataRowView 类型");
                }
                //MessageBox.Show("rowData 的类型是: " + rowData.GetType().ToString());
                // 创建菜单项并设置 Tag 属性
                ToolStripMenuItem planMenuItem = new ToolStripMenuItem("制定计划");

                // 将 rowHandle、rowData 和 columnName 存储在 Tag 中
                planMenuItem.Tag = new { RowHandle = rowHandle, RowData = rowData, ColumnName = columnName };
                // 订阅事件
                planMenuItem.Click += planMenuItemClick;
                
                // 将菜单项添加到上下文菜单
                contextMenuStrip1.Items.Clear();  // 清空以前的菜单项
                contextMenuStrip1.Items.Add(planMenuItem);
                // 显示菜单
                contextMenuStrip1.Show(Control.MousePosition);

            }

        }
        private async void planMenuItemClick(object sender, EventArgs e)
        {
            // 从菜单项的 Tag 属性中获取 rowHandle 和 rowData
            ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
            if (menuItem != null)
            {
                var data = menuItem.Tag as dynamic;
                int rowHandle = data?.RowHandle ?? -1;
                object rowData = data?.RowData;
                string columnName = data?.ColumnName;

                // 存储 rowData 供其他事件处理方法使用
                this.currentRowData = rowData;

                // 处理点击事件
                PlanMenuAdd addpan = new PlanMenuAdd();

                 
                // 将 rowData 和 columnName 传递到添加页面
                addpan.SetRowData(rowData, columnName);
                DialogResult result= addpan.ShowDialog();
                if (result == DialogResult.OK)
                {
                    ProductionPlan_LoadAsync(sender, e);
                }
            }
        }

       

        private void createMenuItemClick(object sender, EventArgs e)
        {
            // 显示提示框
            XtraMessageBox.Show($"正在计划里！");
        }
        private void deleteMenuItemClick(object sender, EventArgs e)
        {
            //// 获取当前菜单项的 Tag 信息
            //var item = (sender as ToolStripMenuItem).Tag;
            //dynamic data = item;
            //int rowHandle = data.RowHandle;
            //string columnName = data.ColumnName;

            //// 打开计划删除窗口
            //PlanMenuDel delete = new PlanMenuDel();
            //delete.Show();
        }
        private void gridControl1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                var view = gridControl1.DefaultView as GridView;
                var info = view.CalcHitInfo(e.Location);
                if (info.InRowCell)
                {
                    contextMenuStrip1.Show(gridControl1.PointToScreen(e.Location));
                }
            }
        }

        private void gridControl1_Click_1(object sender, EventArgs e)
        {

        }
    }
}